<template>
    <el-dialog v-model="visible" class="custom-prompt-dialog" :title="title" width="450">
        <div class="custom-prompt-dialog-body">
            <template v-if="dialogType !== 1">
                <h3>
                    <el-icon><WarningFilled /></el-icon>{{ bodyTitle }}
                </h3>
                <template v-if="isBatch">
                    <p v-if="bodyTip1" class="body-tip1">{{ bodyTip1 }}</p>
                    <p v-if="bodyTip2" class="body-tip2" v-html="bodyTip2"></p>
                </template>
                <template v-else>
                    <p v-if="bodyTip1" class="body-tip1">{{ bodyTip1 }}</p>
                </template>
            </template>
            <template v-else>
                <!-- 转移分组 -->
                <el-form ref="formRef" :model="formData" :rules="rules" label-position="top">
                    <el-form-item label="转移至分组：" prop="group_id">
                        <el-cascader
                            ref="cascaderRef"
                            v-model="formData.group_id"
                            :props="defaultProps"
                            class="w100"
                            :options="groupOptions"
                            @change="orgChange" />
                    </el-form-item>
                </el-form>
            </template>
        </div>
        <template #footer>
            <el-button @click="cancel">取消</el-button>
            <el-button type="primary" @click="confirm">确定</el-button>
        </template>
    </el-dialog>
</template>

<script setup>
import { reactive, ref, defineExpose, computed, onBeforeMount } from 'vue';
import { cloneDeep } from 'lodash';
import {
    collectChecknum,
    collectTransferGroup,
    closeList,
    downloadList,
    delList,
    exportDetail
} from '@/api/highMaterial/collectionTable';
import { ElMessage } from 'element-plus';
import { getGroupList } from '@/api/concreation';
import { useStore } from '@/store';
import { ShowTaskMessage } from '@/hooks/TaskMessageHooks';
import { parabolaAnimation } from '@/utils/parabola';

const store = useStore();
const emit = defineEmits(['confirm']);

const visible = ref(false);
const idList = reactive([]);
const dialogType = ref();
const activeTitle = ref();
const canLength = ref(0);

const isBatch = computed(() => {
    return !activeTitle.value;
});
const typeName = computed(() => {
    // 1转移分组，2结束，3下载，4删除，5导出
    const types = {
        2: '结束',
        3: '下载',
        4: '删除',
        5: '导出'
    };
    return types[dialogType.value];
});
const title = computed(() => {
    if (dialogType.value == 1) {
        return '批量转移分组';
    }
    const mainTitle = isBatch.value ? '批量' : '';
    return `${mainTitle}${typeName.value}提醒`;
});
const bodyTitle = computed(() => {
    const exportTitle = dialogType.value === '导出' ? '明细' : '收集表';
    const mainTitle = isBatch.value ? '所选' : `【${activeTitle.value}】`;
    return `你确定要${typeName.value}${mainTitle}${exportTitle}吗？`;
});
const bodyTip1 = computed(() => {
    let tips;
    if (isBatch.value) {
        tips = {
            2: '仅支持提前结束进行中的收集表，结束后，无法再次启用。',
            3: '仅支持下载未开始和进行中的收集表。',
            4: '进行中收集表不支持删除，仅支持删除未开始和已结束的收集表。',
            5: '仅支持导出进行中和已结束的收集表。'
        };
    } else {
        tips = {
            2: '结束后，无法再次启用。'
        };
    }
    return tips[dialogType.value];
});
const bodyTip2 = computed(() => {
    return `可${dialogType.value == 2 ? '提前' : ''}${typeName.value}所选<span>${canLength.value}</span>个${
        dialogType.value == 2 ? '进行中' : ''
    }收集表${dialogType.value == 3 ? '推广二维码' : ''}${dialogType.value == 5 ? '明细' : ''}，请谨慎操作！`;
});

/* ================================分组================================ */
const groupOptions = reactive([]);
const formRef = ref();
const cascaderRef = ref();
const formData = reactive({
    group_id: ''
});
const rules = reactive({
    group_id: [{ required: true, message: '请选择分组', trigger: 'change' }]
});
const defaultProps = {
    checkStrictly: true, // 是否严格的遵守父子节点不互相关联
    emitPath: false,
    multiple: false,
    label: 'name',
    value: 'id'
};
// 获取活动分组
const onGroupgList = async () => {
    const res = await getGroupList({ type: 27, name: '' });
    groupOptions.length = 0;
    groupOptions.push(...res.data);
};
// 选择完分组后立即关闭
const orgChange = () => {
    cascaderRef.value.togglePopperVisible();
};

onBeforeMount(() => {
    onGroupgList();
});
/* ================================分组================================ */

const cancel = () => {
    formData.group_id = '';
    visible.value = false;
};

const confirm = async e => {
    // loading接口
    let list = ['/scrm-api/console/media/content/collect/list'];
    let fetchApi;
    if (dialogType.value == 1) {
        list = [
            '/scrm-api/console/media/content/collect/transfer-group',
            '/scrm-api/console/tenant/group/getLists',
            ...list
        ];
        fetchApi = collectTransferGroup;
    } else if (dialogType.value == 2) {
        list = ['/scrm-api/console/media/content/collect/batch-close', ...list];
        fetchApi = closeList;
    } else if (dialogType.value == 3) {
        list = [
            '/scrm-api/console/media/content/collect/batch-download',
            '/scrm-api/console/tenant/group/getLists',
            ...list
        ];
        fetchApi = downloadList;
    } else if (dialogType.value == 4) {
        list = [
            '/scrm-api/console/media/content/collect/batch-del',
            '/scrm-api/console/tenant/group/getLists',
            ...list
        ];
        fetchApi = delList;
    } else if (dialogType.value == 5) {
        // todo:导出
        fetchApi = exportDetail;
    }
    store.commit('user/setApiList', list);
    if (dialogType.value == 1) {
        const result = await formRef.value.validate();
        if (result) {
            await fetchApi({ contain_ids: idList, transfer_group_id: formData.group_id });
            cancel();
            emit('confirm', dialogType.value, isBatch.value);
            ElMessage.success('收集表批量转移分组成功');
        }
        return;
    }
    // todo: 接口
    if (isBatch.value) {
        if (!canLength.value) {
            ElMessage.error(`没有可${typeName.value}的收集表`);
            return;
        }
    }
    // todo:不同类型执行不同方法
    await fetchApi({ id: idList });
    cancel();
    emit('confirm', dialogType.value, isBatch.value);
    // todo:异步任务的提示
    if ([3, 5].includes(dialogType.value)) {
        parabolaAnimation(e);
        ShowTaskMessage(`收集表${isBatch.value ? '批量' : ''}${typeName.value}异步任务创建成功`);
    } else {
        ElMessage.success(`收集表${isBatch.value ? '批量' : ''}${typeName.value}成功`);
    }
};

const open = async (type, ids, row) => {
    visible.value = true;
    idList.length = 0;
    if (type != 1 && !row?.title) {
        const res = await collectChecknum({
            ids,
            type: type - 1
        });
        canLength.value = res?.num || 0;
        idList.push(...cloneDeep(res?.legalIds || []));
    } else {
        idList.push(...cloneDeep(ids || []));
    }
    dialogType.value = type / 1;
    activeTitle.value = row.title;
};

defineExpose({
    open
});
</script>
<style lang="scss" scoped>
.custom-prompt-dialog {
    &-body {
        padding: 15px 0;
        min-height: 100px;
        box-sizing: border-box;

        :deep(.w100) {
            width: 95%;
        }

        :deep(.el-form-item__error) {
            padding-top: 12px;
        }

        h3 {
            display: flex;
            align-items: center;
            font-size: 15px;
            color: #555;
            margin-bottom: 10px;

            i {
                font-size: 20px;
                color: #ff6b00;
                margin-right: 8px;
            }
        }

        .body-tip1,
        .body-tip2 {
            font-size: 13px;
            padding-left: 28px;
        }

        .body-tip1 {
            margin-bottom: 10px;
            color: #999;
        }

        .body-tip2 {
            color: #333;

            :deep(span) {
                display: inline-block;
                margin: 0 4px;
                color: #ff6b00;
            }
        }
    }
}
</style>
